﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using SunwellRenderer.Camera;
using Librarinth;

namespace SunwellRenderer.Rendering
{
	public class GBufferRenderer : Renderer
	{
		protected override IEnumerable<string> AllInitialShader
		{
			get
			{
				yield return typeof(BetaShader).Name;
				yield return typeof(LeafShader).Name;
			}
		}

		RenderTarget2D GColor;
		RenderTarget2D GNormal;
		RenderTarget2D GDepth;
		RenderTarget2D GBack;
		protected override void OnLoadContent()
		{
			var device	= SunwellMain.Instance.GraphicsDevice;
			var pp	= device.PresentationParameters;

			GColor	= new RenderTarget2D(device,pp.BackBufferWidth,pp.BackBufferHeight,1,SurfaceFormat.Color
				,pp.MultiSampleType,pp.MultiSampleQuality);

			GNormal	= new RenderTarget2D(device,pp.BackBufferWidth,pp.BackBufferHeight,1,SurfaceFormat.Color
				,pp.MultiSampleType,pp.MultiSampleQuality);

			GDepth	= new RenderTarget2D(device,pp.BackBufferWidth,pp.BackBufferHeight,1,SurfaceFormat.Single
				,pp.MultiSampleType,pp.MultiSampleQuality);

			GBack	= new RenderTarget2D(device,pp.BackBufferWidth,pp.BackBufferHeight,1,SurfaceFormat.HalfVector2
				,pp.MultiSampleType,pp.MultiSampleQuality);
		}

		readonly int ColorRTIndex;
		readonly int NormalRTIndex;
		readonly int DepthRTIndex;
		readonly int BackRTIndex;
		public GBufferRenderer()
		{
			Parent.AllGlobalTexture.GetIndex("GColor",out ColorRTIndex);
			Parent.AllGlobalTexture.GetIndex("GNormal",out NormalRTIndex);
			Parent.AllGlobalTexture.GetIndex("GDepth",out DepthRTIndex);
			Parent.AllGlobalTexture.GetIndex("GBack",out BackRTIndex);
		}

		protected override void Begin(GraphicsDevice device)
		{
			device.RenderState.DepthBufferEnable = true;
			device.RenderState.DepthBufferWriteEnable = true;
			device.RenderState.AlphaBlendEnable = false;
			device.RenderState.AlphaTestEnable = true;
			device.RenderState.ReferenceAlpha = 128;

			device.SetRenderTarget(0,GColor);
			device.SetRenderTarget(1,GNormal);
			device.SetRenderTarget(2,GDepth);
			device.SetRenderTarget(3,GBack);

			device.Clear(Color.TransparentBlack);
		}

		protected override void End(GraphicsDevice device)
		{
			device.SetRenderTarget(0,null);
			device.SetRenderTarget(1,null);
			device.SetRenderTarget(2,null);
			device.SetRenderTarget(3,null);

			Parent.AllGlobalTexture.Datas[ColorRTIndex]	= GColor.GetTexture();
			Parent.AllGlobalTexture.Datas[NormalRTIndex]	= GNormal.GetTexture();
			Parent.AllGlobalTexture.Datas[DepthRTIndex]	= GDepth.GetTexture();
			Parent.AllGlobalTexture.Datas[BackRTIndex]	= GBack.GetTexture();
		}
	}
}